<template>
  <main-card-admin title="活动管理" :loading="globalLoading" :tabs="getTabs()" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button v-auth="'admin-activity-manage-hit-contest-add'" type="primary" @click="handleEdit()">新建</a-button>
    </template>
    <template #screen-space>
      <a-row class="page-top" :wrap="false">
        <a-col class="flex gap-x-8">
          <a-select
            ref="select"
            v-model:value="pageForm.labelId"
            style="width: 140px"
            :options="classOptions"
            :field-names="{ label: 'labelName', value: 'labelId' }"
            @change="getDataList({ offset: 1 })"
          />
          <a-select
            ref="select"
            v-model:value="pageForm.status"
            style="width: 140px"
            :options="statusOptions"
            :field-names="{ label: 'labelName', value: 'labelId' }"
            @change="getDataList({ offset: 1 })"
          />
        </a-col>
        <a-col flex="1" />
        <a-col>
          <a-input
            v-model:value="pageForm.name"
            v-trim
            allow-clear
            placeholder="请输入名称"
            class="w-328"
            @press-enter="getDataList({ offset: 1 })"
          >
            <template #prefix><SearchOutlined /></template>
          </a-input>
        </a-col>
      </a-row>
    </template>
    <div class="search-table w-100%">
      <div class="list-table">
        <a-table
          :columns="tableColumns"
          :data-source="dataList"
          :pagination="false"
          :scroll="{ x: scrollX }"
          :row-key="(r:RecordListItem) => r.id"
          class="header-right-angle admin-table"
          @change="onTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'labelNames'">
              <label-classification :label-list="record.labelNames || []" />
            </template>

            <template v-else-if="column.dataIndex === 'status'">
              {{ record.status === '进行中' ? '进行中..' : record.status }}
            </template>
            <template v-else-if="column.dataIndex === 'date'"> {{ record?.beginTime }} - {{ record?.endTime }} </template>

            <template v-else-if="column.dataIndex == 'docName'">
              <div class="download-wrap" @click="handleDownload(record.id, record?.docUrl, record?.docName)">
                <p :title="record?.docName">{{ record?.docName }}</p>
                <a-button type="link">
                  <i class="iconfont icon-download-2-line"></i>
                </a-button>
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'trainDataName'">
              <div class="download-wrap" @click="handleDownload(record.id, record?.trainDataUrl)">
                <p :title="record?.trainDataName">{{ record?.trainDataName }}</p>
                <a-button type="link">
                  <i class="iconfont icon-download-2-line"></i>
                </a-button>
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'assessmentDataName'">
              <div class="download-wrap" @click="handleDownload(record.id, record?.assessmentDataUrl)">
                <p :title="record?.assessmentDataName">{{ record?.assessmentDataName }}</p>
                <a-button type="link">
                  <i class="iconfont icon-download-2-line"></i>
                </a-button>
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'assessmentCodeName'">
              <div class="download-wrap" @click="handleDownload(record.id, record?.assessmentCodeUrl)">
                <p :title="record?.assessmentCodeName">{{ record?.assessmentCodeName }}</p>
                <a-button type="link">
                  <i class="iconfont icon-download-2-line"></i>
                </a-button>
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'tools'">
              <a-button type="link" style="margin-right: 12px" @click="handleToDetail(record as RecordListItem)">详情</a-button>
              <a-button v-auth="'admin-activity-manage-hit-contest-delete'" type="link" @click="handleDelete(record as RecordListItem)">
                删除
              </a-button>
            </template>
            <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
          </template>
        </a-table>
        <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
      </div>
    </div>
  </main-card-admin>
  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    msg="活动删除后，不可恢复，请确认操作"
    :label="`请输入活动名称`"
    :confirm-name="currentDeleteTaskItem?.name"
    @ok="onOkDeleteTask"
  />
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { computed, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import LabelClassification from '@/components/LabelClassification/index.vue'
  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import useList from '@/hooks/use-list'
  import { adminCollectionApi, adminHitContestApi, fetchDownload, tagManageApi } from '@/services/api'
  import { downloadFile, filterTableColumns, isOffice, replaceEmptyStr, waitLoading } from '@/utils'

  import { getTabs } from '../common'
  import { statusOptions } from '../options'
  import { DictionaryType, PageForm, RecordListItem, TaskStatus } from '../types'

  type SorterType = 'desc' | 'asc'
  const router = useRouter()
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 180
      },
      {
        title: '类型',
        dataIndex: 'labelNames',
        width: 244
      },

      {
        title: '状态',
        dataIndex: 'status',
        width: 120
      },
      {
        title: '描述',
        dataIndex: 'description',
        width: 280
      },
      {
        title: '活动时间',
        dataIndex: 'date',
        width: 200
        // isSort: true
      },
      {
        title: '打榜说明',
        dataIndex: 'docName',
        width: 120
      },
      {
        title: '训练数据',
        dataIndex: 'trainDataName',
        width: 120
      },
      {
        title: '评测数据',
        dataIndex: 'assessmentDataName',
        width: 120
      },
      {
        title: '评测代码',
        dataIndex: 'assessmentCodeName',
        width: 120
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 180,
        isSort: true
      },
      {
        title: '',
        width: 104,
        dataIndex: 'tools',
        fixed: 'right'
      }
    ])
  )

  const scrollX = computed(() => {
    return tableColumns.value.reduce((prev, curr) => {
      return prev + (curr.width as number)
    }, 0)
  })

  /********************类别************************/
  let classOptions = ref<TaskStatus[]>([
    {
      labelName: '全部分类',
      labelId: ''
    }
  ])

  //表格
  const { pageForm, loading, dataList, getDataList } = useList<PageForm, RecordListItem>(
    adminHitContestApi.list,
    {
      name: '',
      labelId: '',
      status: '',
      columns: 'createTime',
      order: 'desc'
    },
    {
      afterCallback: () => {
        dataList.value = dataList.value.map((item: RecordListItem) => {
          item.labelNames = item.labelNames?.map((label: any) => ({ labelId: label, labelName: label })) as any
          return item
        })
      }
    }
  )
  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    let columns = sorter.field
    let order = sorter.order === 'ascend' ? 'asc' : ('desc' as SorterType)
    if (!sorter.order) {
      columns = 'createTime'
      sorter.order = 'desc'
    }
    getDataList({ offset: 1, order, columns })
  }

  //获取字典信息
  const { loading: getDictionLoading, runAsync: getDictionaryRun } = useRequest<ResponseData<DictionaryType[]>>(tagManageApi.list, {
    onSuccess: ({ data }) => {
      classOptions.value = [
        ...classOptions.value,
        ...data.map((item: DictionaryType) => ({ labelName: item.v, labelId: item.id }))
      ] as TaskStatus[]
    }
  })

  //全局Loading
  const globalLoading = computed(() => {
    return loading.value || getDictionLoading.value
  })

  /* 跳转 */
  const handleToDetail = (r: RecordListItem) => {
    window.open(`/hit-contest/detail/${r.id}`)
  }

  // 删除项目案例
  const currentDeleteTaskItem = ref<RecordListItem>()
  const isDeleteDialogShow = ref(false)
  const FAVORITE_TYPE_CASE = 2 //2代表收藏的类型为案例
  const handleDelete = (item: RecordListItem) => {
    currentDeleteTaskItem.value = item
    getCollectionRun({
      favoriteType: FAVORITE_TYPE_CASE,
      objectId: item.id
    })
    isDeleteDialogShow.value = true
  }
  const onOkDeleteTask = async () => {
    const { code } = await adminHitContestApi.del({}, { urlParams: { id: currentDeleteTaskItem.value?.id || '' }, isAddUid: true })
    if (code === 'SYSTEM-100000') {
      message.success('删除成功')
      isDeleteDialogShow.value = false
      getDataList()
    }
  }
  //查询案例收藏人数
  const currentCollection = ref(0)
  const { runAsync: getCollectionRun } = useRequest<ResponseData<number>>(adminCollectionApi.numberOfCollections, {
    onSuccess: ({ data }) => {
      currentCollection.value = data
    }
  })

  //新建
  const handleEdit = () => {
    router.push(`/admin/activity-manage/hit-contest/add`)
  }

  const handleDownload = async (id: string, url: string, name?: string) => {
    const { data } = await adminHitContestApi.download({ id, url })
    // 获取文件名
    if (isOffice(data)) {
      await waitLoading(fetchDownload(data, name || url), {
        loadingText: '数据准备中,请耐心等待...',
        errorText: '文件下载失败',
        successText: '文件下载成功'
      })

      return
    }
    message.success('开始下载')
    downloadFile(data, data)
  }

  getDictionaryRun({
    type: 'rank_type'
  })
  getDataList()
</script>

<style lang="less" scoped>
  .hit-contest {
    width: 100%;
  }

  .list-table {
    overflow: hidden;
    width: 100%;
  }
</style>
